package com.xudow.app.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.newui.bean.UserListStudentMessage;
import com.xudow.app.ui.task.AddToCartListTask;
import com.xudow.app.ui.task.CartStudentChangeTask;
import com.xudow.app.ui.task.CourseToOrderTask;
import com.xudow.app.ui.task.StudentListTask;
import com.xudow.app.util.ImageUtils;
import com.xudow.app.util.Maps;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class ChoseChildActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private ListView childLv;
    private List<UserProfileWithOther>data;
    private RelativeLayout add_rlayout;
    private TextView selectCommit;
    private long studentId=0L;//购物车跳转传递的学生ID
    private long itemId=0L;
    private long courseId=0L;//课程详情跳转传递的新选课程ID
    private long courseId_to_order=0L;//用于生成订单的课程ID
    private childAdapter adapter;
    HashMap<String, String> params;
    private int flag;
    private View footview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chosechild_layout);
        initView();
        studentId= getIntent().getLongExtra("studentId",0L);
        itemId=getIntent().getLongExtra("itemId",0L);
        courseId=getIntent().getLongExtra("courseId",0L);
        courseId_to_order=getIntent().getLongExtra("courseId_to_order",0L);
        flag=getIntent().getIntExtra("FLAGE",0);//flag为1 生成订单,为2添加购物车
        if (0!=courseId_to_order){
            getMyApp().currentOrderId=courseId_to_order;
        }
        data = new ArrayList<UserProfileWithOther>();
        initdata();
    }

    public void goBackClick(View view){
        finish();
    }
    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       if(resultCode==2){
           if(requestCode==1){
               initdata2();
           }
       }
    }

    private void initdata() {
        data = new ArrayList<UserProfileWithOther>();

        StudentListTask getstudent=new StudentListTask(getApplicationContext(),getstudentHandler);
        addTask(getstudent);
        getstudent.execute();
        showLodingDialog("正在处理");
    }
    private void initdata2() {
        data = new ArrayList<UserProfileWithOther>();

        StudentListTask getstudent=new StudentListTask(getApplicationContext(),getstudentHandler2);
        addTask(getstudent);
        getstudent.execute();
        showLodingDialog("正在处理");
    }
    private Handler getstudentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==StudentListTask.SUCCESS){
                Bundle bundle=msg.getData();
                UserProfileWithOther[] arr=(UserProfileWithOther[])bundle.getSerializable("students");

               if (null!=arr&&arr.length>0) {
                   data.addAll(Arrays.asList(arr));
                   adapter.setData(data);
                   add_rlayout.setVisibility(View.GONE);
                   childLv.setVisibility(View.VISIBLE);


               }else {
                   add_rlayout.setVisibility(View.VISIBLE);
                   childLv.setVisibility(View.INVISIBLE);
               }
            }else
                getMyApp().makeToast("网络获取失败");
        }
    };
    private Handler getstudentHandler2=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==StudentListTask.SUCCESS){
                Bundle bundle=msg.getData();
                UserProfileWithOther[] arr=(UserProfileWithOther[])bundle.getSerializable("students");

                if (null!=arr&&arr.length>0) {
                    data.addAll(Arrays.asList(arr));
                    adapter.setData(data);
                    add_rlayout.setVisibility(View.GONE);
                    childLv.setVisibility(View.VISIBLE);

//                   childLv.setItemChecked(0,true);
                    studentId=data.get(0).getId();
                    adapter.notifyDataSetChanged();
                }else {
                    add_rlayout.setVisibility(View.VISIBLE);
                    childLv.setVisibility(View.INVISIBLE);
                }
            }else
                getMyApp().makeToast("网络获取失败");
        }
    };
    private void initView() {
        footview=View.inflate(this,R.layout.item_add_child_layout,null);

        add_rlayout=(RelativeLayout)findViewById(R.id.add_rlayout);
        childLv=(ListView)findViewById(R.id.child_list);
        selectCommit=(TextView)findViewById(R.id.select_commit_tv);
        selectCommit.setOnClickListener(this);
        add_rlayout.setOnClickListener(this);
        adapter=new childAdapter(getApplicationContext(),null);
        childLv.addFooterView(footview);
        childLv.setAdapter(adapter);

        childLv.setOnItemClickListener(this);

    }

    @Override
    public void onClick(View view) {


        switch (view.getId()){

            case R.id.select_commit_tv:
                params = Maps.newHashMap();

                if (flag==1&&courseId_to_order!=0){
                    //TODO 生成订单

                    makeOrder();
                    return;
                }
                if (flag==2&&courseId!=0){//新课程选择学生
                    selectStudent();
                } else if (itemId!=0){ // 提交课程的上课学生修改
                    modifyStudent();
                }
                showLodingDialog("正在处理...");
                break;
            case R.id.add_rlayout:
                goToAddChild();
                break;
        }
    }

    /**
     * 生成订单
     */
    private void makeOrder() {
        if (0!=studentId) {
            params.clear();
//            Log.e("choseChildactivity", "makeOrder: 课程编号" + courseId_to_order + "--学生编号:" + studentId);
            params.put("course_id", Long.toString(courseId_to_order));
            params.put("studentId", Long.toString(studentId));
            CourseToOrderTask makeordertask = new CourseToOrderTask(getApplicationContext(), makeorderhandler);
            addTask(makeordertask);
            makeordertask.execute(params);
            showLodingDialog("正在生成订单");

        }else
            getMyApp().makeToast("请选择孩子");
    }

    /**
     * 生成订单Handler
     */
    private Handler makeorderhandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==CourseToOrderTask.SUCCESS){
               // getMyApp().makeToast("请在30分钟内付款，否则订单会自动取消，同时学兜50元优惠将视为已使用。请谨慎下单。");
               Toast.makeText(ChoseChildActivity.this, "请在30分钟内付款，否则订单会自动取消，同时学兜50元优惠将视为已使用。请谨慎下单。", Toast.LENGTH_LONG).show();
                Intent intent=new Intent(ChoseChildActivity.this,OrderDetailActivity.class);
                intent.putExtra("orderId",(String)(msg.obj));
                startActivity(intent);
            }else {
                String str;
                str=(String) (msg.obj);
                if (null==str||"".equals(str))
                    str="学生选择不成功";
                getMyApp().makeToast(str);
            }
        }
    };
//    /**
//     * 对话框
//     */
//    protected void dialog(String title,int n) {
//        flage=n;
//
//    }
    private void selectStudent() {
        //Log.e("chosechild", "itemId: "+itemId+" courceid:"+courseId+" studentid:"+studentId);
        params.clear();
        params.put("course_id", Long.toString(courseId));
        params.put("studentId", Long.toString(studentId));
        AddToCartListTask selectTask=new AddToCartListTask(getApplicationContext(),selectStudentHandler);
        addTask(selectTask);
        selectTask.execute(params);

    }
    /**
     * 新课程选择学生Handler
     */
    private Handler selectStudentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what== AddToCartListTask.SUCCESS){
                //TODO 提示用户 并关闭当前页面
                getMyApp().makeToast("学生选择成功");
                finish();
            }else{
                String str;
                str=msg.getData().getString("errMessage");
                if (null==str||"".equals(str))
                    str="学生选择不成功";
                getMyApp().makeToast(str);
            }
        }
    };
    /**
     * 修改课程学生
     */
    private void modifyStudent(){

        params.put("item_id", Long.toString(itemId));
        params.put("studentId", Long.toString(studentId));
        CartStudentChangeTask changeTask=new CartStudentChangeTask(getApplicationContext(),
                changeCommitHandler);
        addTask(changeTask);
        changeTask.execute(params);

    }
    /**
     * 修改购物车课程的学生Handler
     */
    private Handler changeCommitHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==CartStudentChangeTask.SUCCESS)
              Toast.makeText(getApplicationContext(),"选择成功",Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(getApplicationContext(),"选择失败",Toast.LENGTH_SHORT).show();
            finish();
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position==data.size()){//添加孩子
            goToAddChild();
        }else{
            studentId=data.get(position).getId();
            adapter.notifyDataSetChanged();
        }

    }

    /**
     *
     */
    private void goToAddChild(){
        Intent intent=new Intent(getApplicationContext(),AddNewStudentActivity.class);
//        startActivity(intent);
        startActivityForResult(intent,1);
    }

    public class childAdapter extends BaseAdapter{

        private List<UserProfileWithOther> data;
        private Context cxt;
        public childAdapter(Context context,List<UserProfileWithOther> list){
            data=list;
            cxt=context;
        }
        public void setData(List<UserProfileWithOther> list){
            this.data=list;
            notifyDataSetChanged();
        }
        @Override
        public int getCount() {
            if (null==data)
                return 0;
            return data.size();
        }

        @Override
        public Object getItem(int i) {
            return data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder=null;

                if (0==studentId&&null!=data)
                      studentId=data.get(0).getId();
            /*if(i==data.size()){
                view=View.inflate(cxt,R.layout.item_add_child_layout,null);
                return view;
            }*/
            if (null==view){
                holder=new Holder();
                view=View.inflate(cxt,R.layout.item_chosechild_list,null);
                holder.child_ico=(ImageView)view.findViewById(R.id.child_ico);
                holder.child_select=(ImageView)view.findViewById(R.id.child_select_img);
                holder.name=(TextView)view.findViewById(R.id.child_name);
                view.setTag(holder);
            }else if (null!=view)
                holder=(Holder)view.getTag();

            UserProfileWithOther child=data.get(i);
                if (null!=child&&null!=holder) {

                        holder.name.setText(child.getName()+"");
                    if (null != child.getPhotoPath()) {
                        String imageUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, child.getPhotoPath());
                        ImageUtils.loadImage(cxt, holder.child_ico, imageUrl, R.mipmap.default_portrait);
                    }
                    if (studentId == child.getId())
                        holder.child_select.setImageResource(R.mipmap.btn_cart_checked);
                    else
                        holder.child_select.setImageResource(R.mipmap.btn_cart_unchecked);
                }
            return view;
        }

        class Holder{
            public TextView name;
            public ImageView child_ico;
            public ImageView child_select;
        }
    }
}
